package com.joehaivo.hweather.View;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.graphics.drawable.DrawableWrapper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.joehaivo.hweather.Presenter.Forecast;
import com.joehaivo.hweather.Presenter.Recycler24hrAdapter;
import com.joehaivo.hweather.Presenter.RecyclerSuggestionAdapter;
import com.joehaivo.hweather.R;
import com.joehaivo.hweather.Presenter.RecyclerAdapter;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements TencentLocationListener, SwipeRefreshLayout.OnRefreshListener {
    String TAG = "TAG";
    String cityName = "萍乡市";
    StringBuilder urlHFWeather;
    StringBuilder urlXZGetNow;
    TextView tmpText;
    TextView sunText, tvAirNum;
    TextView cityText;
    ImageButton addBtn;
    TencentLocationRequest tencentLocationRequest;
    TencentLocationManager locationManager;
    Handler handler;
    SwipeRefreshLayout swipeRefreshLayout;
    SharedPreferences sharedPreferences;
    double localLongitude = 113.817;
    double localLatitude = 27.6;
    RecyclerView forecastRecyclerView;
    RecyclerAdapter recyclerAdapter;
    RecyclerView rv24hrFore;
    RecyclerView rvSuggestion;
    TextView tv24hrDescription;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    AnimationDrawable drawAnime;
    ImageView imageAnime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatus(true);
        setContentView(R.layout.activity_main);
        sunText = (TextView) findViewById(R.id.sunnyText);
        tmpText = (TextView) findViewById(R.id.tmpText);
        tvAirNum = (TextView) findViewById(R.id.air_num);
        cityText = (TextView) findViewById(R.id.cityText);
        addBtn = (ImageButton) findViewById(R.id.btn_setting);
        tv24hrDescription = (TextView)findViewById(R.id.text_24hr_description);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        imageAnime = (ImageView) findViewById(R.id.imageAnime);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
        mSensorManager.registerListener(new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageAnime,"translationX",0,sensorEvent.values[1]*230);
                objectAnimator.setDuration(600);
                objectAnimator.start();
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {
            }
        },mSensor,2000000,2000000);

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
//        swipeRefreshLayout.setProgressViewOffset(true,);
        urlHFWeather = new StringBuilder("https://free-api.heweather.com/v5/forecast?city=");
        //  https://free-api.heweather.com/v5/forecast?city=萍乡市&key=bbeef92e1fe94133b1c298024e7629f5
        urlXZGetNow = new StringBuilder("https://api.seniverse.com/v3/weather/now.json?key=e5e2ngdpmv2eh3p8&location=");
        //彩云天气
        //https://api.caiyunapp.com/v2/7xJkeOW5-lexk1l5/113.817,27.6/forecast.json
        // TencentLoc
        tencentLocationRequest = TencentLocationRequest.create();
        tencentLocationRequest.setRequestLevel(3);
        locationManager = TencentLocationManager.getInstance(getApplicationContext());
        int errorCode = locationManager.requestLocationUpdates(tencentLocationRequest, this);
        sharedPreferences = this.getSharedPreferences("realtimeInfo", MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();

        handler = new Handler() {
            private static final int TAG_SUCCESS_FLAG = 0;
            private static final int TAG_DATE = 1;
            private static final int TAG_FORE_CONDITION = 2;
            private static final int TAG_NOW_CONDITION = 3;
            private static final int TAG_HIGHTMP = 4;
            private static final int TAG_LOWTMP = 5;
            private static final int TAG_NOW_TMP = 6;
            private static final int TAG_IMAGECODE = 7;
            private static final int TAG_HOURLYDESCRIPTION = 8;
            private static final int TAG_LIST = 9;
            private static final int TAG_FORE_CODE = 10;
            private static final int TAG_FORE_HOURLY = 11;
            private static final int TAG_SUGGESTION = 12;
            private static final int TAG_HEFENG_AQI = 13;
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case TAG_SUCCESS_FLAG:
                        if (msg.obj.toString().equals("Succeed")) {
                            Toast.makeText(MainActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                            swipeRefreshLayout.setRefreshing(false);
                        } else if (msg.obj.toString().equals("Failed")) {
                            Toast.makeText(MainActivity.this, "刷新失败", Toast.LENGTH_SHORT).show();
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        break;
                    case TAG_HOURLYDESCRIPTION:
                        tv24hrDescription.setText(msg.obj.toString());
                        editor.putString("hourlyDescription", msg.obj.toString());
                        editor.apply();
                        break;
                    case TAG_NOW_TMP:
                        tmpText.setText(msg.obj + "°");
                        editor.putString("realtimeTmp", msg.obj + "°");
                        editor.apply();
                        break;
                    case TAG_NOW_CONDITION:
                        sunText.setText(msg.obj.toString());
                        editor.putString("realtimeSkycon", msg.obj.toString());
                        editor.apply();
                        break;
                    case TAG_LIST:
                        initRecycler((List<Map<String, Object>>) msg.obj);
                        break;
                    case TAG_FORE_HOURLY:
                        init24hrRecycler((List<Map<String, Object>>) msg.obj);
                        break;
                    case TAG_SUGGESTION:
                        initSuggestionRecycler((List<Map<String,Object>>) msg.obj);
                        break;
                    case TAG_HEFENG_AQI:
                        tvAirNum.setText("空气 "+msg.obj.toString());
                        break;
                }
            }
        };
        setTextfromlocal(sharedPreferences);
    }

    private void initSuggestionRecycler(List<Map<String,Object>> data){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rvSuggestion = (RecyclerView) findViewById(R.id.recyclerViewSuggestion);
        rvSuggestion.setLayoutManager(layoutManager);
        RecyclerSuggestionAdapter recyclerSuggestionAdapter = new RecyclerSuggestionAdapter(this,data);
        rvSuggestion.setAdapter(recyclerSuggestionAdapter);
    }

    private void initRecycler(List<Map<String, Object>> dataList) {
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        forecastRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        forecastRecyclerView.setLayoutManager(layoutManager);
//        forecastRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));//分割线
        recyclerAdapter = new RecyclerAdapter(this);
        recyclerAdapter.initData(dataList);
        forecastRecyclerView.setAdapter(recyclerAdapter);
    }
    private void init24hrRecycler(List<Map<String, Object>> dataList){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rv24hrFore = (RecyclerView) findViewById(R.id.recyclerView24hr);
        rv24hrFore.setLayoutManager(layoutManager);
        Recycler24hrAdapter recycler24hrAdapter = new Recycler24hrAdapter(this,dataList);
        rv24hrFore.setAdapter(recycler24hrAdapter);
    }
    private void setTextfromlocal(SharedPreferences mShared) {
        tv24hrDescription.setText(mShared.getString("hourlyDescription", "暂无数据，请下拉刷新"));
        tmpText.setText(mShared.getString("realtimeTmp", ""));
        sunText.setText(mShared.getString("realtimeSkycon", ""));
    }

    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void btnAddCityClick(View view) {
        Intent intent = new Intent(this, AddCityActivity.class);
        startActivityForResult(intent, 1);
    }

    //获得来自AddActivity返回的城市名
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String result = data.getExtras().getString("result");
        Forecast forecast;
        if (result.equals("北京")) {
            cityText.setText(result);

        }
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        if (TencentLocation.ERROR_OK == i) {
            // 定位成功
            String city = tencentLocation.getCity();
            localLongitude = tencentLocation.getLongitude();
            localLatitude = tencentLocation.getLatitude();
            String district = tencentLocation.getDistrict();
            cityName = city;
            cityText.setText(city);
            onRefresh();
            locationManager.removeUpdates(this);
        } else {
            // 定位失败
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    @Override
    public void onRefresh() {
        if (localLongitude != 0.0) {
            Forecast forecast = new Forecast(this,handler);
            forecast.getCaiyunFore(localLongitude, localLatitude);
            forecast.getHefengNow(cityName);
            forecast.getHefengFore(cityName);
            forecast.getHefengSuggestion(cityName);
            forecast.getHefengAQI(cityName);
        }
    }
}
